<?php
defined('SYSPATH') or die('No direct access allowed.');
/**
 * 处理采购预警的算法
 * 计算一个sku的预警信息
 * @author z
 * 
 */
class Service_Warningcount{
	
	
	/**
	 * 计算最佳下单日期
	 */
	static function Warning(array $sku = NULL)
	{
		if($sku and isset($sku['sku']) and isset($sku['daysales']) and $sku['wave_days'])
		{
		
		//库存信息
		$sku['inventory'] = Inventory::select_stock($sku['sku']);
//      ----------------------------------kdw--------------------------------
		//交期
//		$sku['delivery'] = Service_Warningcount::get_daydelivery($sku['sku']);
        $sku['delivery'] = 7;
//      ------------------------------------kdw-end----------------------------
		//可支持天数
		if((float)$sku['daysales'] > 0)
		{
			$sku['supp_days'] = (float)$sku['inventory']['all_available_num']/(float)$sku['daysales'] - (float)$sku['wave_days'];
		}
		else
		{
			$sku['supp_days'] = 10000;
		}

		$sku['best'] =  $sku['supp_days'] - $sku['delivery'];
				
		}

		return $sku;
	}
	
	
	/**
	 * 获取交期
	 * 
	 */	
	static function get_daydelivery($sku)
	{
//    -------------------------------------kdw--------------------------------
// 		$delivery = DB::select()
// 					->from('erp_providerproducts')
// 					->join('erp_provider')
// 					->on('erp_providerproducts.iproviderID','=','erp_provider.id')
//					->where('erp_provider.state','=',2)//通过的供应商
//					->where('erp_providerproducts.iproductID','=',$sku)
// 					->order_by('erp_providerproducts.price')//最低价格
// 					->execute('readonlyerp')
// 					->current();
//		return isset($delivery['delivery'])?$delivery['delivery']:0;

        $delivery=Newerpclientapi::querySupplierSkuJoin($sku);
        return isset($delivery['delivery'])?$delivery['delivery']:0;
//     ------------------------------------kdw-end-----------------------------
	}

	//获得供应商列表
	static function get_provider_lists($sku)
	{
        if(true)
        {
		return Warningtmp::get_provider_lists($sku);
        }

//      -------------------------------------kdw--------------------------------------
//        return DB::select('erp_provider.vProviderName','erp_providerproducts.*','erp_provider.payment')
// 					->from('erp_providerproducts')
// 					->join('erp_provider')
// 					->on('erp_providerproducts.iproviderID','=','erp_provider.id')
//					->where('erp_provider.state','=',2)//通过的供应商
//					->where('erp_providerproducts.iproductID','=',$sku)
//					// ->where('erp_providerproducts.iproviderID','!=',$provider_defaulut['iproviderID'])
// 					->order_by('erp_providerproducts.price')//最低价格
// 					->execute('readonlyerp')
// 					->as_array();

        //根据sku获取到sku信息和供应商名称
        $supplierskus=Newerpclientapi::querySupplierSkuJoin($sku);
        foreach($supplierskus as $suppliersku){
            $sql="SELECT id,paywayname AS payment FROM payways WHERE id IN
                    (SELECT payways_id FROM supplierpayaccount WHERE supplier_id=".$suppliersku['iproviderID'].")";
            $pays=DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
            $suppliersku['pay']=$pays;
        }
        return $supplierskus;
//      -------------------------------------kdw-end------------------------------------
	}

	//获取在途库存
	static function get_inventory_onway($sku)
	{
		if($sku)
		{
		/* $quantity = DB::select(array(DB::expr('SUM(purchaseorder_details.quantity)'),'quantity'))
		->from('purchaseorders')
		->join('purchaseorder_details')
		->on('purchaseorders.id','=','purchaseorder_details.purchaseorder_id')
		->where('purchaseorders.status','in',array(10,20))
		//->where('purchaseorders.status','!=',50)
		->where('purchaseorder_details.sku','=',$sku)
		->group_by('purchaseorder_details.sku')
		->execute('newerp')
		->current(); */
		
		$onways = 0;
		$sql = "select  purchaseorder_id,quantity,ware_quantity from  purchaseorder_details  where sku='".trim($sku)." '";
		$sql .= " and status<70 ";
		$purchaseorder_ids = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
		if(empty($purchaseorder_ids))return 0;
		
		//找出没有完结的采购量数据，用采购量-入库量；
		foreach ($purchaseorder_ids as $key=>$purchaseorder_id){
			$sql = "select id from purchaseorders where id=".$purchaseorder_id['purchaseorder_id']." and status <70 ";
			$status_temp = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
			
			if(!isset($status_temp['id'])){
				unset($purchaseorder_ids[$key]);
			}else{

					$onways += ($purchaseorder_id['quantity']-$purchaseorder_id['ware_quantity']>0)?($purchaseorder_id['quantity']-$purchaseorder_id['ware_quantity']):0;
			}
		}
		/*foreach ($purchaseorder_ids as $key=>$purchaseorder_id){
			$sql = "select id from purchaseorders where id=".$purchaseorder_id['purchaseorder_id']." and status in(10,20)";
			$status_temp = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
			
			if(!isset($status_temp['id'])){
				unset($purchaseorder_ids[$key]);
			}else{
				$sql = "select sum(warehouse_quantity) as sum_w 
					from warehouseorders 
					where purchaseorders_id=".$purchaseorder_id['purchaseorder_id']." and sku='".trim($sku)."'";
				$warehouse = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
				if(empty($warehouse))
				{
					$onways += $purchaseorder_id['quantity'];
				}else {
					$onways += $purchaseorder_id['quantity'] - $warehouse['sum_w'];
				}
			}
		}*/

		/* $quantity = $quantity ? $quantity['quantity'] : 0;

		$warehouse_quantity = DB::select(array(DB::expr('SUM(warehouseorders.warehouse_quantity)'),'warehouse_quantity'))
		->from('warehouseorders')
		->join('purchaseorders')
		->on('warehouseorders.purchaseorders_id','=','purchaseorders.id')
		->where('purchaseorders.status','in',array(10,20))
		//->where('purchaseorders.status','!=',50)
		->where('warehouseorders.sku','=',$sku)
		->group_by('warehouseorders.sku')
		->execute('newerp')
		->current();

		$warehouse_quantity = $warehouse_quantity ? $warehouse_quantity['warehouse_quantity'] : 0;

		$inventory_onway = $quantity - $warehouse_quantity; */
		return $onways;
		}
	}


	/**
     * @time 20140912
     * 可以废弃了
	 * 保存预警信息
	 * @param array $warning
	 */
	static function save_warning(array $warning)
	{
		if(!$warning or !isset($warning['sku']))
		{
			return;
		}
		$warning_sku = DB::select()
					->from('product_attached')
					->where('sku','=',$warning['sku'])
					->execute('erp_database111')
					->current();
		if($warning_sku)
		{
			//var_dump($warning);
			$warning['updatatime'] = date('Y-m-d H:m:s');

			DB::update('product_attached',array_keys($warning))
			->set($warning)
			->where('sku','=',$warning['sku'])
			->execute('readonlyerp');
		}
		else 
		{
			$warning['createtime'] = date('Y-m-d H:m:s');
			$warning['wave_days'] = 3;
			$warning['target_time'] = 7;

			DB::insert('product_attached',array_keys($warning))
			->values($warning)
			->execute('readonlyerp');
		}
	}
	

}
